﻿using System;
using MessageSystem.Managed.Infrastructure;

namespace MessageSystem.Managed.Serialization
{
    public class MessageFieldTag
    {
        public static void ReadTag(out UInt16 nFieldIndex, out MessageFieldType nFieldType, NetStream ns)
        {
            byte nLowTag = ns.ReadByte();
            if (nLowTag < 0x80)
            {
                nFieldIndex = (UInt16)(nLowTag >> 3);
                nFieldType = (MessageFieldType)(nLowTag & 0x07);
            }
            else
            {
                nFieldIndex = (UInt16)(ns.ReadByte() + 16);
                nFieldType = (MessageFieldType)(nLowTag & 0x07);
            }
        }

        public static void WriteTag(UInt16 nFieldIndex, MessageFieldType nFieldType, NetStream ns)
        {
            // 1 + 4 + 3
            if (nFieldIndex < 16)
            {
                byte nTag = (byte)(nFieldIndex << 3 | (byte)nFieldType);
                ns.WriteByte(nTag);
            }
            else
            {
                // 8 + 1 + 4 + 3
                byte nLowTag = (byte)(0x80 | (byte)nFieldType);
                UInt16 nTag = (UInt16)((nFieldIndex - 16) << 8 | nLowTag);
                ns.WriteUInt16(nTag);
            }
        }
    }
}
